package com.thinkgem.jeesite.modules.gen.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thinkgem.jeesite.common.persistence.BaseConstants;
import com.thinkgem.jeesite.modules.gen.dao.GenTemplateMapper;
import com.thinkgem.jeesite.modules.gen.entity.GenTemplate;
import com.thinkgem.jeesite.modules.gen.entity.GenTemplateRel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 模板配置Service
 *
 * @author kongxiangsheng
 * @version 2018-11-05
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class GenTemplateService extends ServiceImpl<GenTemplateMapper, GenTemplate> implements IService<GenTemplate> {
    @Autowired
    private GenTemplateRelService genTemplateRelService;

    /**
     * 根据id获取（含子表）
     *
     * @param id
     * @return
     */
    public GenTemplate getWithChildren(String id) {
        GenTemplate genTemplate = this.getById(id);
        genTemplate.setGenTemplateRelList(genTemplateRelService.getByGenTemplateId(id));
        return genTemplate;
    }

    /**
     * 保存数据（含子表）
     *
     * @param genTemplate
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWithChildren(GenTemplate genTemplate) {
        this.saveOrUpdate(genTemplate);

        for (GenTemplateRel genTemplateRel : genTemplate.getGenTemplateRelList()) {
            if (genTemplateRel.getId() == null) {
                continue;
            }
            if (BaseConstants.DEL_FLAG_NORMAL.equals(genTemplateRel.getDelFlag())) {
                // TODO: 有没有办法不用加下面这行
                genTemplateRel.setTemplateId(genTemplate.getId());
                genTemplateRelService.saveOrUpdate(genTemplateRel);
            } else {
                genTemplateRelService.removeById(genTemplateRel.getId());
            }
        }
    }

    /**
     * 删除数据（含子表数据）
     *
     * @param genTemplate
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteWithChildren(GenTemplate genTemplate) {
        this.removeById(genTemplate.getId());
        genTemplateRelService.deleteByGenTemplateId(genTemplate.getId());
    }

    /**
     * 查询所有模板（用于字典选择）
     *
     * @return
     */
    public List<GenTemplate> getAllTemplateDict() {
        QueryWrapper queryWrapper = new QueryWrapper<GenTemplate>();
        queryWrapper.select(GenTemplate.COL_ID, "concat(" + GenTemplate.COL_NAME + " ,'-', " + GenTemplate.COL_DESC + ") as " + GenTemplate.COL_NAME);
        return this.list(queryWrapper);
    }

}